package org.nearby.note.dialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.nearby.note.bean.user;
import org.nearby.note.dao.userDaoImpl;
import org.nearby.note.utils.common;

public class RegDlg extends JDialog {
	private static final int win_width = 350;
	private static final int win_height = 220;

	private JPanel mainPanel = new JPanel();
	private JLabel userLabel = new JLabel("用户名：");
	private JTextField userText = new JTextField("");
	private JLabel pwdLabel = new JLabel("密    码：");
	private JPasswordField pwdText = new JPasswordField();

	private JButton regBtn = new JButton("注册");

	private userDaoImpl userImpl = new userDaoImpl();
	
	private JFrame _parent;
	private RegDlg _self = this;

	public RegDlg(JFrame parent, String title, boolean modal) {
		super(parent, title, modal);
		_parent = parent;
		
		initWin();
		initBind();
	}

	public void initWin() {
		mainPanel.setBounds(0, 0, 350, 150);
		mainPanel.setLayout(null); // 绝对定位

		userLabel.setBounds(40, 20, 70, 30);
		userText.setBounds(120, 20, 150, 30);
		pwdLabel.setBounds(40, 70, 70, 30);
		pwdText.setBounds(120, 70, 150, 30);
		regBtn.setBounds(120, 120, 100, 30);

		mainPanel.add(userLabel);
		mainPanel.add(userText);
		mainPanel.add(pwdLabel);
		mainPanel.add(pwdText);
		mainPanel.add(regBtn);

		this.add(mainPanel);

		this.setSize(win_width, win_height);
		this.setResizable(false);
		HashMap<String, Integer> d = common.getWindowCenterSize(win_width,
				win_height);
		this.setLocation(d.get("width"), d.get("height"));
		this.setVisible(true);
	}

	public void initBind() {
		regBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				user u = new user(userText.getText().trim(), pwdText.getText()
						.trim());
				int resultCode = userImpl.regUser(u);
				switch (resultCode) {
					case -2:
						JOptionPane.showMessageDialog(getContentPane(), "用户名或密码不能为空");
					break;
					case -1:
						JOptionPane.showMessageDialog(getContentPane(), "注册失败，用户名已经被注册!");
						clearText();
					break;
					case 0:
						JOptionPane.showMessageDialog(getContentPane(), "注册失败!");
						clearText();
					break;
					default:
						JOptionPane.showMessageDialog(getContentPane(), "注册成功!");
						_self.dispose();
				}
			}
		});
	}
	private void clearText(){
		this.userText.setText("");
		this.pwdText.setText("");
	}
	/*
	 * public static void main(String[] args){ new RegDlg(null, "注册", false); }
	 */
}
